/*******************************************************************************
 * Copyright 2010 Ray Ling
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package org.ring.rinject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.ring.rinject.collection.Wrapper;
import org.ring.rinject.exception.RinjectException;

public class RinjectWrapper extends Wrapper<Object> {

	public RinjectWrapper(Object obj) {
		super(obj);
	}

	@SuppressWarnings("unchecked")
	public <R> Class<R> targetAsClass() {
		return (Class<R>) target;
	}

	@SuppressWarnings("unchecked")
	public <R> R newObject() throws RinjectException {

		try {
			if (target instanceof Class<?>) {
				Class<?> c = (Class<?>) target;

				return (R) c.newInstance();
			} else {
				throw new InstantiationException("RinjectWrapper target["
						+ target + "] should be a class.");
			}
		} catch (IllegalAccessException iae) {
			throw new RinjectException("Target[" + target
					+ "] is not a class type or can't create new instance");
		} catch (InstantiationException ie) {
			throw new RinjectException("Target[" + target
					+ "] is not a class type or can't create new instance");
		}
	}

	@SuppressWarnings("unchecked")
	public <R> R callMethod(Object... params) throws RinjectException {
		try {
			Method method = (Method) target;
			return (R) method.invoke(null, params);
		} catch (InvocationTargetException ite) {
			throw new RinjectException("Target[" + target
					+ "] is not a method type or can't invoke method");
		} catch (IllegalAccessException iae) {
			throw new RinjectException("Target[" + target
					+ "] is not a method type or can't invoke method");
		}
	}

}
